import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet("/myreq")
public class MyReqServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");
        StringBuilder builder = new StringBuilder();
        // 得到请求的协议和版本号
        builder.append("协议：" + req.getProtocol() + "<br>");
        // 得到请求的类型
        builder.append("Method：" + req.getMethod() + "<br>");
        // 得到 uri
        builder.append("URI：" + req.getRequestURI() + "<br>");
        builder.append("URL：" + req.getRequestURL() + "<br>");
        builder.append("ContextPath：" + req.getContextPath() + "<br>");
        builder.append("QueryString：" + req.getQueryString() + "<br>");
        builder.append("<hr><h2>请求头</h2>");
        // 得到所有的请求类型（headerNames）和请求值
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) { // 判断还有没有 head name
            String headName = headerNames.nextElement();
            // 得到 head value
            String headValue = req.getHeader(headName);
            builder.append(headName + ": " + headValue + "<br>");
        }
        builder.append("<hr>");
        builder.append("参数：" + req.getParameter("name") + "<br>");
        resp.getWriter().write(builder.toString());
    }
}